#include "Tabla.h"


Tabla::~Tabla() {
}


Tabla::Tabla(int tamaniotabla){
	this->tamanio=tamaniotabla;
    for(unsigned int x=0; x<tamanio; x++) {
        tablaNrosBuckets.push_back(x);
    }
}


unsigned int Tabla::tamanioTabla(){
	return this->tablaNrosBuckets.size();
}


unsigned int Tabla::obtenertd(int nrobucket){
	int contarbucket=0;
	for(unsigned int x=0; x<tamanio; x++) {
		int valor=tablaNrosBuckets[x];
		//cout<<valor<<endl;
	    if  (valor==nrobucket) contarbucket++;
	 }
	if (contarbucket>0) return (tamanio/contarbucket);
	return 1;
}


unsigned int Tabla::calcularNroBucket(Key key){
	return (key.obtenerClave() % tamanio);
}


void Tabla::modificar(int pos,int valor){
	tablaNrosBuckets[pos]=valor;
}

int Tabla::obtener(int pos){
	return tablaNrosBuckets[pos];
}

unsigned int Tabla::duplicarTabla(){
	for(unsigned int x=0; x<tamanio; x++) {
		int valor=tablaNrosBuckets[x];
	    tablaNrosBuckets.push_back(valor);
	 }
	tamanio=tamanio*2;
	return tamanio;
}


unsigned int Tabla::reducirTabla(){
	if (tamanio>4){
		tamanio=tamanio/2;
		for(unsigned int x=0; x<tamanio; x++) {
	    tablaNrosBuckets.pop_back();
		} return tamanio;
	}
	return tamanio;
}


int Tabla::obtenerNroBucket(Key key){
	unsigned int pos = calcularNroBucket(key);

	return tablaNrosBuckets[pos];
}

void Tabla::mostrar(){
	cout <<"[";
	for(unsigned int x=0; x<tablaNrosBuckets.size(); x++) {
	cout << " "<<tablaNrosBuckets[x]<<" ";
	}
	cout<<"]"<<endl;
 }

std::vector<int> Tabla::getTabla(){
	return this->tablaNrosBuckets;
}


void Tabla::setTabla(std::vector<int> tabla){
	tablaNrosBuckets=tabla;
}

unsigned int Tabla::guardarTabla(string nombreArch){
	std::ofstream FILE(nombreArch.c_str(), std::ios::out | std::ofstream::binary);
	std::copy(tablaNrosBuckets.begin(), tablaNrosBuckets.end(), std::ostreambuf_iterator<char>(FILE));
	return 0;
}


unsigned int Tabla::cargarTabla(string nombreArch){
	std::ifstream INFILE(nombreArch.c_str(), std::ios::in | std::ifstream::binary);
	std::vector<int> data((std::istreambuf_iterator<char>(INFILE)), std::istreambuf_iterator<char>());
	setTabla(data);
}

